<template>
  <el-dialog title="提示" :visible.sync="addRoleDialog" width="50%" @close="AddRuleClose">
    <el-form
      :model="addRuleForm"
      :rules="addRuleRules"
      ref="AddRuleRef"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="addRuleForm.roleName"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="addRuleForm.roleDesc"></el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="addRoleDialog = false">取 消</el-button>
      <el-button type="primary" @click="addRules">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
export default {
  props: {
    visible: {
      type: Boolean
    }
  },
  data() {
    return {
      addRoleDialog: false,
      addRuleForm: {
        roleName: '',
        roleDesc: ''
      },
      addRuleRules: {
        roleName: [
          { required: true, message: '请输入角色名', trigger: 'blur' },
          { min: 2, max: 10, message: '请输入2~10个字符', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 2, max: 10, message: '请输入2~10个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {},
  methods: {
    // 关闭对话框
    AddRuleClose() {
      this.$refs.AddRuleRef.resetFields()
    },
    // 添加角色
    addRules() {
      this.$refs.AddRuleRef.validate(async valid => {
        if (!valid) return false
        const { data: res } = await this.$http.post('roles', this.addRuleForm)
        if (res.meta.status !== 201) {
          return this.$message.error('添加角色失败')
        }
        this.$message.success('添加成功')
        this.addRoleDialog = false
        this.$emit('addRuleSuccess')
      })
    }
  },
  watch: {
    visible: function(val) {
      this.addRoleDialog = val
    },
    addRoleDialog: function(val) {
      this.$emit('update:visible', val)
    }
  }
}
</script>
<style lang="less" scoped>
</style>
